﻿using FileManagerSystem.Helper;
using FileManagerSystem.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Net;
using System.Threading.Tasks;

namespace FileManagerSystem.Middleware
{
    /// <summary>
    /// 功能描述 :Api全局异常捕获中间件
    /// </summary>
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAysnc(context, ex);
            }
        }

        private static async Task HandleExceptionAysnc(HttpContext context, Exception exception)
        {
            if (exception == null)
            {
                return;
            }
            await WriteExceptionAsync(context, exception);
        }

        private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
        {
            //日志记录错误
            NLog.LogManager.GetLogger("GlobalException").Error(context.Request.Path + " |" + exception.StackTrace.ToString());

            //返回友好的提示
            context.Response.ContentType = "application/json;charset=utf-8";
            context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            string msgJson = JsonHelper.ObjectToJSON(exception.Message);
            await context.Response.WriteAsync(msgJson);
        }
    }
}
